package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.domain.user;
import com.example.service.impl.userServiceImpl;
import com.example.tool.CreatJwt;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.catalina.filters.ExpiresFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.List;

@CrossOrigin
@RestController
public class userController {

    @Autowired
    userServiceImpl userServiceimpl;

    /**
     * 测试
     * */
    @GetMapping("/test1")
    public Object test1(HttpServletRequest request){
        JSONObject jsonObject=new JSONObject();
        //获取token
        String token = request.getHeader("token");
        //解密token
        Claims claims = Jwts.parser()
                .setSigningKey("my-123")
                .parseClaimsJws(token)
                .getBody();
        String id = claims.getId();
        String username = claims.getSubject();

        user u = new user();
        u.setUser_id(id);
        u.setUser_pw(username);
        System.out.println(u);
        if (username!=null && claims.getId() != null && username.equals(username))
        {
            jsonObject.put("code",200);
            return jsonObject;
        }else {
            jsonObject.put("code",500);
            return jsonObject;
        }
    }

    /**
     * 用户登录接口
     *
     * */
    @PostMapping("/userLogin")
    public Object userLogin(@RequestBody user u, HttpServletResponse response){
        JSONObject jsonObj = new JSONObject();
        u = userServiceimpl.findAll(u);
        if (u != null){
            //设置token
            String token = CreatJwt.getToken(u);
            jsonObj.put("code", true);
            jsonObj.put("status", "登陆成功");
            jsonObj.put("username", u.getUser_id());
            jsonObj.put("token", token);
            return jsonObj;
        }else{
            jsonObj.put("code", false);
            jsonObj.put("status", "用户名或密码错误");
            return jsonObj;
        }
    }

    /**
     * 用户注册
     *
     * */
    @PostMapping("/resUser")
    public Object resUser(HttpServletRequest request,@RequestBody user u){
        JSONObject jsonObject = new JSONObject();

        if(userServiceimpl.judgeUserId(u.getUser_id()) == null){
            int rows = userServiceimpl.resUser(u);
            jsonObject.put("rows", rows);
            jsonObject.put("message", "注册成功");
        }else{
            jsonObject.put("rows", 0);
            jsonObject.put("message", "有人使用了此用户名");
        }

        return jsonObject;
    }

    @PostMapping("/test2")
    public void test2(HttpServletRequest request, @RequestBody String t1){
        System.out.println(t1);
        System.out.println(request.getHeader("token"));
    }
}
